<template>
  <div class="login-box">
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="ruleForm.password"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="authCode" class="auth-box">
        <el-input v-model.number="ruleForm.authCode"></el-input>
        <el-button @click="getAuth">获取验证码</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getAuthCode, Login } from "@/api";
import { mapMutations } from 'vuex'
import {userInfo} from '@/utils'

export default {
  data() {
    return {
      ruleForm: {},
      rules: {
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        authCode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(['CHANGE_ROUTER_LIST', 'CHANGE_USER_INFO']),
    submitForm(formName) {
      // validate  验证输入框内容
      this.$refs[formName].validate((valid) => {
        // valid:true验证成   false  验证失败
        if (valid) {
          Login(this.ruleForm).then((res) => {
            // 登录成功添加token
            localStorage.setItem("token", res.data);

            // 成功提示
            this.$message.success(res.msg);

            // 获取用户信息
            userInfo()

            // 跳转页面
            this.$router.push("/");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 获取验证码
    getAuth() {
      getAuthCode().then((res) => {
        this.$message({ message: `验证码为:${res.data}` });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-box {
  width: 500px;
  border: 1px solid #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding-top: 22px;
}

.auth-box {
  // ::v-deep 样式名称:深度修改组件样式 一般用于修改ui组件默认样式
  ::v-deep .el-form-item__content {
    display: flex;
  }
}
</style>